package com.example.minefieldkeepercloud.util;


import android.graphics.Color;

import com.example.minefieldkeepercloud.R;
import com.example.minefieldkeepercloud.bean.LineChartTestBean;
import com.example.minefieldkeepercloud.view.MyMarkerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.util.ArrayList;
import java.util.List;


/**
 * 曲线图
 * Created by Administrator on 2018/6/21.
 */

public class DynamicLineChartManager {
    private LineChart lineChart;
    private YAxis leftAxis;
    private YAxis rightAxis;
    private XAxis xAxis;
    private LineData lineData;
    private LineDataSet lineDataSet;
    private List<ILineDataSet> lineDataSets = new ArrayList<>();
    private List<String> timeList = new ArrayList<>(); //存储x轴的时间
    private MyMarkerView mv;
//    private Map<Integer, String> xMap;//存储x轴显示的时间


    private int Xmax;//x轴点最大个数
    private String unit;//单位
    //多条曲线
    public DynamicLineChartManager(LineChart mLineChart, List<String> names, List<Integer> colors, int Xmax, String unit) {
        this.lineChart = mLineChart;
        this.Xmax=Xmax;
        this.unit=unit;
        leftAxis = lineChart.getAxisLeft();

        rightAxis = lineChart.getAxisRight();
        xAxis = lineChart.getXAxis();
        initLineChart();
        initLineDataSet(names, colors);

    }

    /**
     * 初始化LineChar
     */
    private void initLineChart() {

        lineChart.setDrawGridBackground(false);
        //显示边界
        lineChart.setDrawBorders(false);
        //设置chart边框线颜色
        lineChart.setBorderColor(R.color.black3);
        //设置是否可以拖拽
        lineChart.setDragEnabled(true);
        //设置chart边框线宽度
        lineChart.setBorderWidth(1f);
        //设置是否可以缩放 x和y，默认true
        lineChart.setScaleEnabled(false);
        //折线图例 标签 设置

        //设置chart动画
        lineChart.animateXY(1000, 1000);
        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);


        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        xAxis.setLabelCount(5, true);
//        xAxis.setLabelCount(5);
        xAxis.setTextColor(R.color.black3);
       xAxis.setTextSize(8);

        xAxis.setGridColor(R.color.black3);
        xAxis.setAvoidFirstLastClipping(true);//图表将避免第一个和最后一个标签条目被减掉在图表或屏幕的边缘


        //x轴数据
//        xMap = new HashMap<>();
//        final String[] valueArry = {"字符串1", "字符串2", "字符串3", "字符串4", "字符串5"};
//        //下边if判断是为了使setLabelCount起作用：坐标数量/x轴标签数量 = 每个标签坐标数量，如果最后两个标签坐标数量相差大于对于5
//        // setLabelCount就显示不正常，也就是每个label要大概平均分配setLabelCount才能正常显示设置的标签数量
//        for (int i = 0; i < timeList.size(); i++) {
//            if (i < 7) {
//                xMap.put((int) i, valueArry[0]);
//            } else if (i < 14) {
//                xMap.put((int) i, valueArry[1]);
//            } else if (i < 21) {
//                xMap.put((int) i, valueArry[2]);
//            } else if (i < 28) {
//                xMap.put((int) i, valueArry[3]);
//            } else if (i < 35) {
//                xMap.put((int) i, valueArry[4]);
//            }
//        }

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (timeList.size() == 0)
                    return "";
                return timeList.get((int) value % timeList.size());
            }
        });

        //保证Y轴从0开始，不然会上移一点
        leftAxis.setAxisMinimum(0f);
        rightAxis.setAxisMinimum(0f);

        //自定义的MarkerView对象
        mv = new MyMarkerView(lineChart.getContext(), R.layout.mymarklayout,unit);
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
    }


    /**
     * 初始化折线（多条线）
     *
     * @param names
     * @param colors
     */
    private void initLineDataSet(List<String> names, List<Integer> colors) {

        for (int i = 0; i < names.size(); i++) {
            lineDataSet = new LineDataSet(null, names.get(i));
            lineDataSet.setColor(colors.get(i));
            lineDataSet.setLineWidth(1.5f);
            lineDataSet.setCircleRadius(2.5f);
            lineDataSet.setCircleColor(R.color.system_color);
            if (i==0||i==(names.size()-1))
            {
                lineDataSet.setDrawCircles(false);

            }else {
                //设置是否画圆
                lineDataSet.setDrawCircles(true);

            }



            //设置线一面部分是否填充颜色
            lineDataSet.setDrawFilled(false);
            //设置是否显示点的坐标值
            lineDataSet.setDrawValues(false);
           //设置填充的背景
//            lineDataSet.setFillDrawable(lineChart.getContext().getResources().getDrawable(R.drawable.fade_white));

            //设置填充的颜色
//            lineDataSet.setFillColor(Color.WHITE);
//           lineDataSet.setFillAlpha(50);


            lineDataSet.enableDashedHighlightLine(5f, 0f, 0f);//点击后的高亮线的显示样式
            lineDataSet.setDrawHorizontalHighlightIndicator(false);
            lineDataSet.setHighLightColor(R.color.system_color);
            lineDataSet.setHighlightLineWidth(0.5f);//设置点击交点后显示高亮线宽
            lineDataSet.setHighlightEnabled(true);//是否禁用点击高亮线




            //lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
            lineDataSet.setValueTextSize(10f);
            lineChart.getLegend().setEnabled(false);
            lineDataSets.add(lineDataSet);

        }

        //添加一个空的 LineData
        lineData = new LineData();
        lineChart.setData(lineData);
        lineChart.invalidate();

    }

    /**
     * 动态添加数据（多条折线图）
     *
     * @param dataBeen
     */
    public void addEntry(LineChartTestBean dataBeen) {

        if (lineDataSets.size() > 0 && lineDataSets.get(0).getEntryCount() == 0) {
            lineData = new LineData(lineDataSets);
            lineChart.setData(lineData);
        }
        String time=dataBeen.getDt();
        timeList.add(time);
        mv.setTimeList(timeList);

        Entry entry = new Entry(lineDataSet.getEntryCount(), dataBeen.getFilingNumber());



        lineData.addEntry(entry, 0);




        lineData.notifyDataChanged();
        lineChart.notifyDataSetChanged();
        lineChart.setVisibleXRangeMaximum(Xmax);
        lineChart.setVisibleXRangeMinimum(Xmax);
        lineChart.moveViewToX(lineData.getEntryCount() - Xmax+1);


    }


    /**
     *有 断点的折线
     *
     * @param listlist
     */
    public void addAllEntry( List<List<LineChartTestBean>> listlist) {

        if (lineDataSets.size() > 0 && lineDataSets.get(0).getEntryCount() == 0) {
            lineData = new LineData(lineDataSets);
            lineChart.setData(lineData);
        }



                for (int j = 0; j <listlist.get(0).size() ; j++) {
                    String time=listlist.get(0).get(j).getDt();
                    timeList.add(time);
                    mv.setTimeList(timeList);
                    Entry entry = new Entry(lineDataSet.getEntryCount(), listlist.get(0).get(j).getFilingNumber());
                    lineData.addEntry(entry, 0);
                    for (int i = 1; i <listlist.size()-1; i++) {
                        boolean isbreak=false;
                        for (int k = 0; k <listlist.get(i).size() ; k++) {
                            if (listlist.get(i).get(k).getDt().equals(time)){
                                lineData.addEntry(entry, i);
                                isbreak=true;
                                break;
                            }
                        }
                        if (isbreak)
                        {
                            break;
                        }
                    }

                    lineData.addEntry(entry, listlist.size()-1);


                }













        lineData.notifyDataChanged();
        lineChart.notifyDataSetChanged();
        lineChart.setVisibleXRangeMaximum(Xmax);
        lineChart.setVisibleXRangeMinimum(Xmax);
        lineChart.moveViewToX(lineData.getEntryCount() - Xmax+1);


    }
    /**
     * 设置Y轴值
     *
     * @param max
     * @param min
     * @param labelCount
     */
    public void setYAxis(float max, float min, int labelCount) {
        if (max < min) {
            return;
        }
        if (max==0)
            max=4;
        leftAxis.setAxisMaximum(max*2);
        leftAxis.setAxisMinimum(min);
        leftAxis.setLabelCount(labelCount, true);
        leftAxis.setTextColor(R.color.black3);
        leftAxis.setGridColor(R.color.black3);

        rightAxis.setEnabled(true);
        rightAxis.setGridColor(Color.argb(0, 255, 255, 255));
        rightAxis.setTextSize(18);
        rightAxis.setTextColor(Color.argb(0, 255, 255, 255));
        lineChart.invalidate();
    }

    /**
     * 设置高限制线
     *
     * @param high
     * @param name
     */
    public void setHightLimitLine(float high, String name, int color) {
        if (name == null) {
            name = "高限制线";
        }
        LimitLine hightLimit = new LimitLine(high, name);
        hightLimit.setLineWidth(4f);
        hightLimit.setTextSize(10f);
        hightLimit.setLineColor(color);
        hightLimit.setTextColor(color);
        leftAxis.addLimitLine(hightLimit);
        lineChart.invalidate();
    }

    /**
     * 设置低限制线
     *
     * @param low
     * @param name
     */
    public void setLowLimitLine(int low, String name) {
        if (name == null) {
            name = "低限制线";
        }
        LimitLine hightLimit = new LimitLine(low, name);
        hightLimit.setLineWidth(4f);
        hightLimit.setTextSize(10f);
        leftAxis.addLimitLine(hightLimit);
        lineChart.invalidate();
    }

    /**
     * 设置描述信息
     *
     * @param str
     */
    public void setDescription(String str) {
        Description description = new Description();
        description.setText(str);
        lineChart.setDescription(description);
        lineChart.invalidate();
    }
}

